<?php
/**
 * Created by PhpStorm.
 * User: kongqi
 * Date: 2019/12/2
 * Time: 23:31
 */

namespace App\Plugin\HostServer\Front;

use App\Plugin\HostServer\Models\PnHostSvDomainOrder;
use App\Plugin\HostServer\Models\PnHostSvDomainSeting;
use App\Plugin\HostServer\Models\PnHostSvGood;
use App\Plugin\HostServer\Models\PnHostSvUser;
use App\Plugin\HostServer\Models\PnHostSvUserLog;
use App\Plugin\HostServer\Services\DomainService;
use App\TraitClass\CheckFormTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Plugin\HostServer\Models\PnHostSvOrder;
use App\Plugin\HostServer\Services\NotifyService;

class UserOrderController extends BaseController
{
    use CheckFormTrait;

    //购买服务器
    public function buyGood(Request $request)
    {
        $data = $request->all();
        $check_data = [
            'id' => ['required', 'numeric'],
            'buy_password' => ['required'],
            'month' => ['required', 'numeric'],
            'system_name' => 'required'
        ];

        $error = $this->checkForm($data, $check_data, [], [
            'id' => '产品',
            'buy_password' => '交易密码',
            'month' => '月数',
            'system_name' => '系统版本'
        ]);
        if (count($error) > 0) {
            $errors = $this->checkFormErrorFormat($error);
            return $this->returnErrorApi($errors['msg']);
        }
        if ($data['month'] <= 0) {
            return $this->returnErrorApi('续费月数必须大于1');
        }
        //验证交易密码
        $buy_password = $data['buy_password'];
        //悲观锁住
        $user = PnHostSvUser::lockForUpdate()->find(user('id', 'host_server'));
        if ($user['buy_password'] != $buy_password) {
            return $this->returnErrorApi('交易密码不正确');
        }
        $good = PnHostSvGood::checked()->find($data['id']);
        if (empty($good)) {
            return $this->returnErrorApi('商品不存在');
        }
        $money = $good->money * $data['month'];
        //验证余额
        if ($user['money'] < $money) {
            return $this->returnErrorApi('您的账号余额不足,您当前余额:' . $user['money']);
        }
        //ok,进行下单
        DB::beginTransaction();
        $order_data = [
            'order_sn' => date('YmdHis') . mt_rand(1000, 9999),
            'model_id' => $good->id,
            'model_type' => 'pn_host_server_good',
            'user_id' => $user['id'],
            'user_name' => $user['name'],
            'name' => $good['name'],
            'money' => $good['money'],
            'total' => $money,
            'month' => $data['month'],
            'system' => implode("", $data['system_name']),
            'user_mark' => $data['user_mark'] ?? '',
            'status' => 3,//等待审核
            'buy_at' => date('Y-m-d H:i:s'),
            'end_at' => date('Y-m-d H:i:s', strtotime($data['month'] . " month")),
            'data' => json_encode($good->toArray())
        ];

        $system_data = [
            'user_id' => $user['id'],
            'money' => $money,
            'name' => '新购服务器',
            'pay_ok_at' => date('Y-m-d H:i:s'),
            'status' => '1',
            'type' => '2'
        ];
        try {
            $order = PnHostSvOrder::buyServer($order_data, $system_data, $user);
            if ($order) {
                DB::commit();
                //发送邮件通知
                $message = [
                    'user_name' => $user['name'] . '(' . $user['email'] . ')',
                    'type' => 'server',
                    'total' => $money,
                    'name' => $good['name'],
                    'month' => $data['month'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'order' => $order,
                    'order_id' => $order->id

                ];

                NotifyService::orderNotifySiteUser($user['name'] . '购买了服务器', $message);

                return $this->returnOkApi('下单成功', ['url' => plugin_route('hostserver.user.order')]);
            }
            DB::rollBack();
            return $this->returnErrorApi('下单失败,请重试');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->returnErrorApi('下单失败,请重试，错误' . $exception->getMessage());
        }

    }

    //查看服务器详情
    public function buyGoodShow($id)
    {

        $user_id = user('id', 'host_server');
        $order = PnHostSvOrder::where('user_id', $user_id)->find($id);
        if (empty($order)) {
            return $this->returnError('401', '不属于你的订单',
                plugin_route('hostserver.user.order'));
        }
        $data = json_decode($order->data, 1);
        $this->setSeo($order->name, $order->name, $order->name);
        $data = [
            'data' => $data,
            'show' => $order
        ];
        return $this->display($data);
    }

    //续费服务器详情
    public function buyGoodRenewal($id)
    {

        $user_id = user('id', 'host_server');
        $order = PnHostSvOrder::where('user_id', $user_id)->with('from')->find($id);

        if (empty($order)) {
            return $this->returnError('401', '不属于你的订单',
                plugin_route('hostserver.user.order'));
        }
        $this->setSeo($order->name, $order->name, $order->name);
        //获取这个产品，如果这个被删除，那么取旧的数据，如果存在则用新的数据
        $good = $order->from;

        if (empty($goods)) {
            $good = json_decode($order['data'], 1);
        } else {
            $good = $good->toArray();
        }

        $data = [
            'show' => $good,
            'order' => $order
        ];
        return $this->display($data);
    }

    //续费POST
    public function renewalGood(Request $request)
    {
        $data = $request->all();
        $check_data = [
            'id' => ['required', 'numeric'],
            'order_id' => ['required', 'numeric'],
            'buy_password' => ['required'],
            'month' => ['required', 'numeric']

        ];

        $error = $this->checkForm($data, $check_data, [], [
            'id' => '产品',
            'buy_password' => '交易密码',
            'month' => '月数',
            'order_id' => '订单'

        ]);
        if (count($error) > 0) {
            $errors = $this->checkFormErrorFormat($error);
            return $this->returnErrorApi($errors['msg']);
        }
        if ($data['month'] <= 0) {
            return $this->returnErrorApi('续费月数必须大于1');
        }

        //验证交易密码
        $buy_password = $data['buy_password'];
        //悲观锁住
        $user = PnHostSvUser::lockForUpdate()->find(user('id', 'host_server'));
        $order = PnHostSvOrder::lockForUpdate()->where('user_id', $user['id'])->find($data['order_id']);
        if (empty($order)) {
            return $this->returnErrorApi('订单不存在');
        }
        if ($user['buy_password'] != $buy_password) {
            return $this->returnErrorApi('交易密码不正确');
        }
        $good = PnHostSvGood::checked()->find($data['id'])->toArray();

        if (empty($good)) {


            $good = json_decode($order->data, 1);
        }
        $money = $good['money'] * $data['month'];
        //验证余额
        if ($user['money'] < $money) {
            return $this->returnErrorApi('您的账号余额不足,您当前余额:' . $user['money']);
        }

        try {
            //ok,进行下单
            DB::beginTransaction();
            //更新订单
            //+过期时间

            $r = PnHostSvOrder::renewalGood($money, $order, $data['month'], $user);
            if ($r) {
                DB::commit();
                //发送邮件通知
                $message = [
                    'user_name' => $user['name'] . '(' . $user['email'] . ')',
                    'type' => 'server_renewal',
                    'total' => $money,
                    'name' => $good['name'],
                    'month' => $data['month'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'order_id' => $order->id
                ];

                NotifyService::orderNotifySiteUser($user['name'] . '续费了服务器', $message);

                return $this->returnOkApi('续费申请成功', ['url' => plugin_route('hostserver.user.order')]);
            }
            DB::rollBack();
            return $this->returnErrorApi('续费申请失败,请重试');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->returnErrorApi('续费申请失败,请重试，错误' . $exception->getMessage());
        }

    }

    //注册域名
    public function buyDomain(Request $request)
    {
        $domain = $request->input('domain');
        if (!$domain) {
            return back();
        }
        //获取价格
        $api = new DomainService();
        $r = $api->search($domain, '1', [], '1');

        if (empty($r['data'])) {
            return $this->returnError('404', '获取不到数据', plugin_route('hostserver.domain.index'));
        }
        if (isset($r['data']['has']) && $r['data']['has']) {
            return $this->returnError('401', '域名已被注册了', plugin_route('hostserver.domain.index'));

        }
        $data = [
            'title' => '注册' . $request->input('domain'),
            'show' => $r['data']
        ];
        return $this->display($data);
    }

    //购买域名POST
    public function buyDomainPost(Request $request)
    {
        $data = $request->all();
        $check_data = [
            'domain' => ['required'],
            'year' => ['required'],
            'username' => 'required',
            'buy_password' => 'required',

        ];

        $error = $this->checkForm($data, $check_data, [], [
            'domain' => '域名',
            'year' => '年数',
            'username' => '持有人',
            'buy_password' => '交易密码',

        ]);
        if (count($error) > 0) {
            $errors = $this->checkFormErrorFormat($error);
            return $this->returnErrorApi($errors['msg']);
        }
        if ($data['year'] <= 0) {
            return $this->returnErrorApi('续费年限必须大于1');
        }
        //验证交易密码
        $buy_password = $data['buy_password'];
        //悲观锁住
        $user = PnHostSvUser::lockForUpdate()->find(user('id', 'host_server'));
        if ($user['buy_password'] != $buy_password) {
            return $this->returnErrorApi('交易密码不正确');
        }

        $domain = $request->input('domain');
        //获取域名数据
        $api = new DomainService();
        try {
            $r = $api->search($domain, '1', [], 1);

            if ($r['data']['has']) {
                return $this->returnErrorApi('已被注册或不可用');
            }
            if ($r['data']['price'] <= 0) {
                return $this->returnErrorApi('已被注册或不可用');
            }
            //取得产品价格
            //判断年限
            if ($data['year'] > 1) {
                $total = $r['data']['renewal_price'] * ($data['year'] - 1) + $r['data']['price'];
            } else {
                $total = $r['data']['price'];
            }

            //验证余额
            if ($user['money'] < $total) {
                return $this->returnErrorApi('您的账号余额不足,您当前余额:' . $user['money']);
            }

            //写入订单
            $order_data = [
                'check_year_numbers'=> $data['year'],
                'user_id' => $user['id'],
                'order_sn' => date('YmdHis') . mt_rand(1000, 9999),
                'user_name' => $user['name'],
                'name' => $data['domain'],
                'domain_user' => $data['username'],
                'money' => $r['data']['oprice'] - 1000,//成本价
                'total' => $total,
                'year_numbers' => $data['year'],
                'status' => 1,
                'buy_at' => date('Y-m-d H:i:s'),
                'end_at' => date('Y-m-d H:i:s', strtotime($data['year'] . " year")),
            ];
            $system_data = [
                'user_id' => $user['id'],
                'money' => $total,
                'name' => '注册域名',
                'pay_ok_at' => date('Y-m-d H:i:s'),
                'status' => '1',
                'type' => '5'//注册域名
            ];
            DB::beginTransaction();
            $r = PnHostSvDomainOrder::buyServer($order_data, $system_data, $user);
            if ($r) {
                DB::commit();
                $o_status = 1;
                //发起注册
                $rp_data = $api->regist($domain, $data['year']);
                if ($rp_data['code'] == 1) {
                    DB::rollBack();
                    return $this->returnErrorApi($rp_data['msg']);
                } elseif ($rp_data['code'] == 90) {
                    $o_status = 3;
                    //更新订单为审核
                    PnHostSvDomainOrder::where(['id' => $r['id']])->update(['status' => 3]);
                }
                //发送邮件通知
                $message = [
                    'user_name' => $user['name'] . '(' . $user['email'] . ')',
                    'type' => 'domain',
                    'total' => $total,
                    'name' => $order_data['name'],
                    'year' => $data['year'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'order' => $r,
                    'order_id' => $r->id,
                    'status' => $o_status
                ];
                NotifyService::orderNotifySiteUser($user['name'] . '注册了域名', $message);
                $back_url = plugin_route('hostserver.user.order.domain');
                return $this->returnOkApi('注册成功', ['url' => $back_url]);
            } else {
                DB::rollBack();
                return $this->returnErrorApi('注册失败，请重试');
            }

        } catch (\Exception $exception) {
            DB::rollBack();

            return $this->returnErrorApi('提交失败' . $exception->getMessage());
        }

    }

    //续费域名
    public function renewalDomain($id)
    {

        if (!$id) {
            return back();
        }
        $order = PnHostSvDomainOrder::where('user_id',user('id','host_server'))->find($id);
        if ($order->status != 1) {
            return back();
        }

        $data = [
            'title' => '续费' . $order['name'],
            'show' => $order
        ];
        //续费价格
        $data['money'] = PnHostSvDomainOrder::renewalMoney($order['total']);
        //取得续费价格
        $api = new DomainService();
        $price = $api->searchSystem($order['name'], 1, [], 1, 1);
        try {
            $data['price'] = $price['data'];

            return $this->display($data);
        } catch (\Exception $exception) {
            return back();
        }

    }

    //续费域名POST
    public function renewalDomainPost(Request $request)
    {
        $data = $request->all();
        $check_data = [
            'domain' => ['required'],
            'year' => ['required'],
            'id' => 'required',
            'buy_password' => 'required',

        ];

        $error = $this->checkForm($data, $check_data, [], [
            'domain' => '域名',
            'year' => '年数',
            'id' => '产品',
            'buy_password' => '交易密码',

        ]);
        if (count($error) > 0) {
            $errors = $this->checkFormErrorFormat($error);
            return $this->returnErrorApi($errors['msg']);
        }
        //验证交易密码
        $buy_password = $data['buy_password'];
        //悲观锁住
        $user = PnHostSvUser::lockForUpdate()->find(user('id', 'host_server'));
        if ($user['buy_password'] != $buy_password) {
            return $this->returnErrorApi('交易密码不正确');
        }
        $id = $request->input('id');
        $order = PnHostSvDomainOrder::where('user_id', $user['id'])->find($id);
        if (empty($order)) {
            return $this->returnErrorApi('不能续费别人的域名');
        }
        if ($data['year'] <= 0) {
            return $this->returnErrorApi('续费年限必须大于1');
        }
        //取得系统金额
        $api = new DomainService();
        $price = $api->searchSystem($order['name'], 1, [], 1, 1);
        if (!isset($price['data'])) {
            return $this->returnErrorApi('获取续费失败');
        } else {
            if ($price['data']['price'] <= 0 || $price['data']['renewal_price'] <= 0) {
                return $this->returnErrorApi('获取续费价格失败');
            }
        }
        if ($data['year'] > 1) {
            $total = $price['data']['renewal_price'] * ($data['year'] - 1) + $price['data']['price'];
        } else {
            $total = $price['data']['price'];
        }

        //验证余额
        if ($user['money'] < $total) {
            return $this->returnErrorApi('您的账号余额不足,您当前余额:' . $user['money']);
        }

        //发起续费
        $result = $api->renewal($order['name'], $data['year']);
        if ($result['code'] == 1) {
            return $this->returnErrorApi($result['msg']);

        }

        //进行下单续费
        //ok,进行下单
        DB::beginTransaction();
        //更新订单
        $r = PnHostSvDomainOrder::renewalGood($total, $order, $data['year'], $user);
        $o_status = 1;
        try {
            if ($r) {

                if ($result['code'] == 90) {
                    $o_status = 4;//续费待审核
                    //更新订单为审核
                    PnHostSvDomainOrder::where(['id' => $r['id']])->update(['status' => $o_status]);
                }
                DB::commit();
                //发送邮件通知
                $message = [
                    'user_name' => $user['name'] . '(' . $user['email'] . ')',
                    'type' => 'domain_renewal',
                    'total' => $total,
                    'name' => $order['name'],
                    'year' => $data['year'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'order_id' => $order->id,
                    'status' => $o_status
                ];

                NotifyService::orderNotifySiteUser($user['name'] . '续费了域名', $message);

                return $this->returnOkApi('续费域名成功', ['url' => plugin_route('hostserver.user.order.domain')]);
            }
            DB::rollBack();
            return $this->returnErrorApi('续费失败,请重试');
        } catch (\Exception $exception) {
            DB::rollBack();

            return $this->returnErrorApi('续费失败,请重试，错误' . $exception->getMessage());
        }

    }
    //查看域名信息
    public function buyDomainShow($id)
    {
        if (!$id) {
            return back();
        }
        $order = PnHostSvDomainOrder::where('user_id',user('id','host_server'))->find($id);
        $handel=$order->info?$order->info()->first()->toArray()??[]:[];
        $content=empty($handel)?'':json_decode($handel['content'],1);
        $data = [
            'title' => '查看' . $order['name'],
            'show' => $order,
            'info'=>$handel,
            'content'=>$content
        ];
        return $this->display($data);
    }
    public function  domainHandle($id,Request $request){
        if (!$id) {
            return back();
        }
        //验证
        $data = $request->all();
        $check_data = [
            'type'=>'required'
        ];
        if($data['type']==1)
        {
            $check_data['main_record_data.*.ip']=['required'];
            $check_data['main_record_data.*.type']='required';

            $check_data['subdomain.*.ip']=['sometimes','required'];
            $check_data['subdomain.*.name']=['sometimes','required'];
        }elseif($data['type']==2)
        {
            $check_data['dns.*']=['required'];
        }
        elseif($data['type']==3)
        {

            $check_data['forward_url']=['required','url'];
            $check_data['forward_type']=['required'];

        }elseif($data['type']==4)
        {
            $check_data['stealth_url']=['required','url'];
            $check_data['stealth_title']=['required'];
        }


        $error = $this->checkForm($data, $check_data, [], [
            'type' => '类型',
            'main_record_data.*.ip' => '主机域名IP',
            'main_record_data.*.type' => '主机域名类型',
            'subdomain.*.ip' => '子域名IP',
            'subdomain.*.name' => '子域名前缀',
            'buy_password' => '交易密码',
            'dns.*' => 'NDS服务地址',
            'forward_type'=>'转发类型',
            'stealth_url'=>'跳转到网页',
            'forward_url'=>'跳转地址',
            'stealth_title'=>'网站标题'

        ]);
        if (count($error) > 0) {
            $errors = $this->checkFormErrorFormat($error);
            return $this->returnErrorApi($errors['msg']);
        }


        $order = PnHostSvDomainOrder::where('user_id',user('id','host_server'))->find($id);
        if(empty($order))
        {
            return $this->returnErrorApi('不存在该域名');
        }
        $domain=$order['name'];
        $api=new DomainService();

        //判断域名设置是否存在了，不存在则添加
        $domain_handle=PnHostSvDomainSeting::where('order_id',$order->id)->where('domain',$domain)->first();
        if(empty($domain_handle))
        {
            $domain_handle=new PnHostSvDomainSeting();
            $domain_handle->domain=$domain;
            $domain_handle->order_id=$order->id;
            $domain_handle->user_id=$order->user_id;
        }
        $domain_handle->type=$data['type'];


        $domain_handle->content=json_encode($data);


        switch ($data['type'])
        {
            case 1:
                $r=$api->ip($domain,$data);
                break;
            case 2:
                $r=$api->dns($domain,$data);
                break;
            case 3:
                $r=$api->stealthUrl($domain,$data);
                break;
            case 4:
                $r=$api->setStealth($domain,$data);
                break;
        }
        if($r['code']==200)
        {
            $or=$domain_handle->save();
        }else{
            $or=0;
        }
        if($or)
        {
            return $this->returnOkApi('设置成功',['url'=>plugin_route('hostserver.user.order.domain')]);

        }else{
            return $this->returnErrorApi($r['msg']);
        }

    }

}